import java.io.IOException;
import java.net.ServerSocket;
import java.util.*;


/**
* The main server for IPCards. Listens for connections from clients.
* Contains the {@link Room} which contains the {@link Table} objects.
* 
* @author Ricky Vincent
*/
public class CardsServer implements Runnable {
	
	private int port = Model.DEFAULT_PORT;
	private ServerSocket server;
	public static Vector<Client> clients;
	private Model model;
	
	private boolean serverRunning = true;
	
	
	public boolean connected() {
		return clients.size()>0;
	}
	
	
	/*
<<<<<<< .working
	
	// game variables
	private Room room;
	//private List<Player> players = new ArrayList<Player>();	
	private Player player;
	// private Map<Player,Set<Card>> selectedCards = new HashMap<PlayerData,Set<Card>>(); 	
	//private Set<Card> selectedCards = new HashSet<Card>(); 
	private PlayerData pd;
	
	private static int snapX = 5;
	private static int snapY = 5;
	private static int snapRatio = 4;
	
	public CardsServer() throws java.rmi.RemoteException {
		this(1099);
	}
	
	public CardsServer(int port) throws java.rmi.RemoteException {
		Table t = new Table();
		t.addDeck(new Deck(t,"PlayingCards"));
		room = new Room(t);
		masterMode(port);
	}
	
=======
>>>>>>> .merge-right.r221
*/
	/**
	 * Constructs a new server to listen for connections from clients on the specified port.
	 * @param port The port to listen for incoming connections.
	 * @throws IOException 
	 */
	public CardsServer (int port, Model model) throws IOException {
		this.model = model;
		this.port = port;
		server = new ServerSocket(port);
		clients = new Vector<Client>();
	}
	
	/**
	 * Constructs a new server to listen for connections from clients.
	 * Listens on the default port.
	 * @throws IOException 
	 */
	public CardsServer (Model model) throws IOException {
		this.model = model;
		server = new ServerSocket(port);
	}
	
	/**
	 * Listens for incoming connections. Creates a new {@link Client} object for each new connection.
	 */
	private void listen() {
		Client newClient;
		
		//infinite loop
		while (serverRunning) {
			
			try {
				newClient = new Client(server.accept(), model.getRoom().getTable());
				Thread thread = new Thread(newClient);
				thread.start();
				clients.add(newClient);
				//////
				
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
	}

	/**
	 * Implemented from <code>Runnable</code> interface. Called when thread starts.
	 */
	public void run() {
		listen();
	}
	
	/**
	 * Stops this server.
	 */
	public void stopServer() {
		try {
			server.close();
			serverRunning = false;
		} catch (IOException e) {
			//Already stopped?
			serverRunning = false;
		}
	}

	/**
	 * @return the model
	 */
	public Model getModel() {
		return model;
	}
}



